
const { exec } = require('../db/mysql')
/* 
author：作者
kerword：关键词


*/

// 获取博客列表
const getList = (author, keyword) => {
    // 返回假数据（保证数据的格式是正确的）
    /* 
       1=1 :因为下面有判断语句，不写1=1会发生拼接报错
    
    */
    let sql = `select * from blogs where 1=1 `
    if (author) {
        sql += `and author = '${author}'`
    }
    if (keyword) {
        sql += `and title like '%${keyword}%'`
    }
    sql += `order by createtime desc`

    // 返回的是一个promise
    return exec(sql)
}

// 获取博客详情
const getDetail = (id) => {
    const sql = `select * from blogs where id = '${id}' `
    return exec(sql).then(rows => {
        // 把数组变成对象的格式
        return rows[0]
    })
}

// 新建博客
const newBlog = (blogData = {}) => {
    // return {
    //     id: 3 //新建博客 插入到数据表里的id
    // }
    const title = blogData.title;
    const author = blogData.author;
    const content = blogData.content;
    const createTime = Date.now()

    const sql = `insert into blogs (title,concent,createtime,author) value('${title}','${content}','${createTime}','${author}')`
    return exec(sql).then(inserData => {
        return {
            id: inserData.inserId
        }
    })
}

// 修改博客
/* 
    id是更新的博客的id
    blogdata是一个博客的对象，包含title  content
*/
const updateBlog = (id, blogData = {}) => {
    // return true
    const title = blogData.title;
    const content = blogData.content;
    const sql = `update blogs set title = '${title}',content = '${content}' where id = '${id}'`
    return exec(sql).then(updateData => {
        if (updateData.affectedRows > 0) {
            return true
        }
        return false //true是成功  false是失败
    })
}

// 删除博客
const delBlog = (id, author) => {
    // return true
    const sql = `delete from blogs where id = '${id}' or author = '${author}'`
    return exec(sql).then(deleteData => {
        // updateData.affectedRows >0判断是否修改成功（即大于1），d如果成功
        if (deleteData.affectedRows > 0) {
            return true
        }
        return false //true是成功  false是失败
    })
}
module.exports = {
    getList,
    getDetail,
    newBlog,
    updateBlog,
    delBlog
}